﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using TigerAndGoats.Framework;

namespace TigerAndGoats.Sprites
{
    public class Piece
    {
        protected GraphNode _location;
        protected Bitmap _image;
        protected Bitmap _image_Gray;

        protected List<DestinationTip> _reachableDestinations = new List<DestinationTip>();

        private bool _isPutup = false;
        public bool IsPutup { get
            {
                return _isPutup;
            } 
        }

        public static Piece Empty = new Piece();
        public static Piece currentPutUp = Piece.Empty;

        public Bitmap GetImage()
        {
            return _image;
        }

        public GraphNode SetLocation(GraphNode location)
        {
            _location = location;
            return _location;
        }

        public GraphNode GetLocation()
        {
            return _location;
        }

        public virtual void Draw(Graphics graphics)
        {

        }

        protected Point GetPointByOrdinate(string ordinate)
        {
            if (!string.IsNullOrWhiteSpace(ordinate))
            {
                string[] ordinateArray = ordinate.Split(',');
                if (ordinateArray != null && ordinateArray.Length >= 2)
                {
                    int x;
                    int.TryParse(ordinateArray[0], out x);
                    int y;
                    int.TryParse(ordinateArray[1], out y);
                    return new Point(ChequerGraph.GetLeftTopPoint().X + GlobalSettings.STEP_LENGTH * x, ChequerGraph.GetLeftTopPoint().Y + GlobalSettings.STEP_LENGTH * y);
                }
            }

            return ChequerGraph.GetLeftTopPoint();
        }

        protected Point GetPieceLocation(Point leftTopPoint, Size pieceSize)
        {
            return new Point(leftTopPoint.X - pieceSize.Width / 2, leftTopPoint.Y - pieceSize.Height / 2);
        }

        public virtual void PutUp(Action action = null)
        {
            _isPutup = true;
            Piece.currentPutUp = this;
            action?.Invoke();
            ChequerGraph.RefreshUI();
        }

        public virtual void PutDown()
        {
            _isPutup = false;
            Piece.currentPutUp = Piece.Empty;

            // 取消提示
            foreach (var reachableDestination in _reachableDestinations)
            {
                reachableDestination.GetLocation().SetPieceEmpty();
            }

            _reachableDestinations.Clear();
            ChequerGraph.RefreshUI();
        }
        
        public decimal GetPutupRatio()
        {
            if (_isPutup)
            {
                return 1 + 0.2m;
            }
            else
            {
                return 1;
            }
        }
    }
}
